package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VisitorsVo;
import com.tanhua.server.exeception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author SunSun
 * @date 2021/10/25
 */
@Service
public class MovementService {

    @DubboReference
    private MovementApi movementApi;



    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private VisitorsApi visitorsApi;




    public void publishMovement(Movement movement, MultipartFile[] imageContent) throws IOException {

        if(StringUtils.isEmpty(movement.getTextContent())){
            throw  new BusinessException(ErrorResult.contentError());
        }

        Long userId = UserHolder.getUserId();

        List<String> list =new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String upload = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            list.add(upload);
        }

        movement.setUserId(userId);
        movement.setMedias(list);

        String movementId = movementApi.publish(movement);

        mqMessageService.sendAudiMessage(movementId);

    }


    @Autowired
    private  MqMessageService mqMessageService;
    /**
     * 查询个人动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findById(Long userId, Integer page, Integer pagesize) {



        PageResult pr=movementApi.findByUserId(userId,page,pagesize);

        List<Movement> items = (List<Movement>) pr.getItems();

        List<MovementsVo> list=new ArrayList<>();

        for (Movement item : items) {
            UserInfo byid = userInfoApi.findByid(item.getUserId());
            MovementsVo vo=MovementsVo.init(byid,item);
            list.add(vo);
        }

        pr.setItems(list);
        return pr;
    }

    /**
     * 查看朋友动态
     * @return
     */
    public PageResult findFriendMovement(Integer page,Integer pagesize) {
        Long userId = UserHolder.getUserId();
        List<Movement> list=movementApi.findFriendMovement(userId,page,pagesize);

        return getPageResult(page, pagesize, list);

    }

    private PageResult getPageResult(Integer page, Integer pagesize, List<Movement> list) {
        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }
        List<Long> movements = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(movements, null);

        List<MovementsVo>  vos=new ArrayList<>();

        for (Movement movement : list) {
            UserInfo userInfo = byIds.get(movement.getUserId());
            if(userInfo!=null){
                MovementsVo vo=MovementsVo.init(userInfo,movement);
                //修复点赞bug
                String key= Constants.MOVEMENTS_INTERACT_KEY+movement.getId();
                String hashkey=Constants.MOVEMENT_LIKE_HASHKEY+UserHolder.getUserId();

                if(redisTemplate.opsForHash().hasKey(key,hashkey)){
                    vo.setHasLiked(1);
                }
                vos.add(vo);
            }
        }

        return new PageResult(page,pagesize,0L,vos);
    }

    public PageResult findRecommendMovements(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        String rediskey=Constants.MOVEMENTS_RECOMMEND +userId;
        String redisvalue = redisTemplate.opsForValue().get(rediskey);
        List<Movement> lists=Collections.EMPTY_LIST;
        if (StringUtils.isEmpty(redisvalue)){
            lists=movementApi.randomMovements(pagesize);
        }else {
            String[] split = redisvalue.split(",");

            if((page-1)*pagesize<redisvalue.length()){
                List<Long> pids = Arrays.stream(split).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                lists=movementApi.findMovementsByPids(pids);
            }

        }

        return getPageResult(page,pagesize,lists);
    }

    public MovementsVo findOne(String movementID) {

        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0202","movement",movementID);
        Movement movement= movementApi.findOne(movementID);
        if(movement!=null){
            UserInfo userInfo = userInfoApi.findByid(movement.getUserId());
            MovementsVo vo =MovementsVo.init(userInfo,movement);
            return vo;
        }else {
            return null;
        }

    }

    /**
     * 谁看过我
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        String key=Constants.VISITORS_USER;
        String hashKey= String.valueOf(UserHolder.getUserId());
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        Long date=StringUtils.isEmpty(value)?null: Long.valueOf(value);
        List<Visitors> list=visitorsApi.queryVisitors(date,UserHolder.getUserId());
        List<Long> visitorUserId = CollUtil.getFieldValues(list, "visitorUserId", Long.class);

        Map<Long, UserInfo> map = userInfoApi.findByIds(visitorUserId, null);

        List<VisitorsVo> vos=new ArrayList<>();
        for (Visitors aLong : list) {
            UserInfo userInfo = map.get(aLong.getVisitorUserId());
            if(userInfo!=null){
                if (!userInfo.getId().equals(UserHolder.getUserId())){
                    VisitorsVo vo = VisitorsVo.init(userInfo, aLong);
                    vos.add(vo);
                }

            }
        }
        return vos;
    }
}
